package com.alexrnl.BetaSeriesFileManager.API;

import java.util.HashMap;
import java.util.List;

import org.w3c.dom.Document;

import com.alexrnl.BetaSeriesFileManager.API.communication.APIParametersKeys;
import com.alexrnl.BetaSeriesFileManager.API.communication.APIParametersKeys.Shows;
import com.alexrnl.BetaSeriesFileManager.API.communication.APIParametersKeys.Shows.Search;
import com.alexrnl.BetaSeriesFileManager.API.communication.QueryManager;
import com.alexrnl.BetaSeriesFileManager.API.dao.ShowDAO;
import com.alexrnl.BetaSeriesFileManager.API.dao.interfaces.IShowDAO;
import com.alexrnl.BetaSeriesFileManager.API.entities.Show;
import com.alexrnl.BetaSeriesFileManager.API.interfaces.IBetaSeries;

/**
 * 
 * @author Alex
 */
public class BetaSeriesXML implements IBetaSeries {

	private static final String	API_KEY		= "4b4b65a6071d";
	private static final String	USER_AGENT	= "BetaSeriesFileManager";
	private static final String	HOST		= "https://api.betaseries.com";

	private final QueryManager	queryManager;
	private final IShowDAO		showDAO;

	/**
	 * Default constructor.
	 */
	public BetaSeriesXML () {
		final HashMap<String, String> compulsoryParams = new HashMap<String, String>();
		compulsoryParams.put(APIParametersKeys.KEY, API_KEY);
		compulsoryParams.put(APIParametersKeys.USER_AGENT, USER_AGENT);

		queryManager = new QueryManager(HOST, compulsoryParams);
		showDAO = new ShowDAO();
	}

	@Override
	public String getStatus () {
		Document doc;
		try {
			doc = queryManager.execute(APIParametersKeys.STATUS().toString());
		} catch (final BetaSeriesAPIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return doc.getElementsByTagName("version").item(0).getTextContent();
	}

	@Override
	public List<Show> searchShows (final String title) {
		if (title == null)
			throw new NullPointerException("You cannot search a null show.");
		if (title.length() <= 2)
			throw new IllegalArgumentException(
					"You cannot search a show with less than 2 caracters.");

		final HashMap<String, String> params = new HashMap<>();
		params.put(Search.TITLE(), title);
		Document doc;
		try {
			doc = queryManager.execute(Shows.SEARCH().getMethod(), params);
		} catch (final BetaSeriesAPIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		System.out.println(doc.getElementsByTagName("url").item(0).getTextContent());
		// TODO Auto-generated method stub
		return showDAO.searchShows(doc);
	}

}
